package com.leigang.resource.config;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

@Component
@Slf4j
public class RequestLimitAspect {

    @Autowired
    private  RedissonClient redissonClient;

    @Pointcut("@annotation(requestLimit)")
    public void pointcut(RequestLimit requestLimit) {
    }

    @Before(value = "pointcut(requestLimit)", argNames = "joinPoint,requestLimit")
    public void before(JoinPoint joinPoint, RequestLimit requestLimit) {
        log.info("RequestLimitAspect before ...");
        String methodName = joinPoint.getSignature().toShortString();
        String key = "submit:" + methodName;
    }

    @Around(value = "pointcut(requestLimit)", argNames = "joinPoint,requestLimit")
    public Object handleDuplicateSubmit(ProceedingJoinPoint joinPoint, RequestLimit requestLimit) throws Throwable {
        log.info("RequestLimitAspect handleDuplicateSubmit ...");
        // 获取方法参数和注解值
        Object[] args = joinPoint.getArgs();
        String methodName = joinPoint.getSignature().toShortString();
        String annotationValue = requestLimit.value();

        // 构造锁名，可以根据实际情况进行适当修改
        String lockName = "duplicateSubmit:" + methodName + ":" + annotationValue;
        long annotationValueLong = Long.parseLong(annotationValue);

        // 尝试获取分布式锁
        RLock lock = redissonClient.getLock(lockName);
        boolean isLocked = false;
        try {
            isLocked = lock.tryLock(0, annotationValueLong, TimeUnit.SECONDS);
            if (isLocked) {
                // 执行原方法
                return joinPoint.proceed(args);
            } else {
                throw new RuntimeException("请勿重复提交！");
            }
        } finally {
            if (isLocked) {
                // 释放分布式锁
                lock.unlock();
            }
        }
    }
}
